-- UIDungeonGoodsEquip
-- Create by luohj Jan/8/2015
-- 地牢商品详细信息界面

require "game/ui/base/TextColorM"

-- UIDungeonGoods继承自Layer
UIDungeonGoodsEquip = class("UIDungeonGoodsEquip", function()
    return cc.Layer:create();
end);

function UIDungeonGoodsEquip.create(pos, shopType, goodsIndex, goodsId)
    return UIDungeonGoodsEquip.new(pos, shopType, goodsIndex, goodsId);
end

-- 构造函数
function UIDungeonGoodsEquip:ctor(pos, shopType, goodsIndex, goodsId)
    self:setName("UIDungeonGoodsEquip");

    -- 初始化
    local node = cc.CSLoader:createNode("layout/shop/GoodsEquipDetail.csb");
    self:addChild(node);
    self.node = node;

    self:setLocalZOrder(UIMgr.TOP_MENU_ZORDER + 2);

    -- 记录商品信息
    self.pos        = pos;
    self.shopType   = shopType;
    self.goodsId    = goodsId;
    self.goodsIndex = goodsIndex;

    -- 注册事件处理回调函数
    self:registerEventCallback();

    -- 注册点击事件
    self:registerTouchEvent();

    -- 重绘
    self:redraw();

    -- 适配
    self:resize();
end

-- 注册事件处理回调函数
function UIDungeonGoodsEquip:registerEventCallback()
    -- 界面析构后，需要清理下
    self:registerScriptHandler(function(ev)
        if ev == "exit" then
            cclog("UIDungeonGoodsEquip 界面析构清理");
            EventMgr.removeAll("UIDungeonGoodsEquip");
        end
    end);
end

-- 注册点击事件
function UIDungeonGoodsEquip:registerTouchEvent()
    -- 注册返回按钮点击事件
    local btnBack = findChildByName(self.node, "BT/btn_back");
    local function onBackClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            -- 关闭当前界面
            AudioM.playFx("button_return");
            UIMgr.getCurrentScene():removeFormByName(self:getName());
        end
    end
    AddBackEventHandler(self, btnBack, onBackClick);
    TextStyleM.setTextStyle(btnBack, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    btnBack:setTitleText(getLocStr("btn_text_back"));

    -- 注册确认购买按钮点击事件
    local btnBuy = findChildByName(self.node, "CT/btn_buy");
    local function onBuyClick(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            AudioM.playFx("button_click");
            -- 尝试购买
            self:tryBuy();
        end
    end
    btnBuy:addTouchEventListener(onBuyClick);

    TextStyleM.setTextStyle(btnBuy, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_BROWN_YELLOW, true);
    if string.startWith(self.shopType, "showcase") then
        -- 解除封印
        btnBuy:setTitleText(getLocStr("unlock_seal"));
    else
        -- 确认购买
        btnBuy:setTitleText(getLocStr("confirm_to_buy"));
    end
end

-- 重绘
function UIDungeonGoodsEquip:redraw()
    -- 显示商品名称
    local CT = findChildByName(self.node, "CT");
    local nameLabel = CT:getChildByName("name");
    local goods = DungeonShopM.queryGoods(self.goodsId);
    local classId = goods[2];
    local goodNum = goods[3];
    local itemInfo = ItemM.query(classId);

    local nameDesc;
    if goodNum > 1 then
        nameDesc = string.format(getLocStr("item_bonus_format"), itemInfo["name"], goodNum);
    else
        nameDesc = itemInfo["name"];
    end

    TextStyleM.setTextStyle(nameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
    nameLabel:setString(nameDesc);

    -- 显示装备描述
    local descLabel = CT:getChildByName("desc");
    local desc = ItemM.getItemDesc(classId);

    TextStyleM.setTextStyle(descLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
    descLabel:setString(desc);
    descLabel = applyString(descLabel, desc);

    -- 商品详情
    local detail = "";
    local detailLabel = CT:getChildByName("detail");
    local equipInfo = EquipM.query(classId);
    local props = EquipM.calcBaseProp(ME.user, classId);
    if #props == 0 then
        detail = ItemM.getItemDesc(classId);
    else
        detail = EquipM.getEquipPropDesc(props);
    end
    TextStyleM.setTextStyle(detailLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE);
    detailLabel:setString(detail);
    detailLabel = applyString(detailLabel, detail);

    -- 设置套装显示
    local suitNameLabel   = CT:getChildByName("suit_name");
    local suitSubLabel    = CT:getChildByName("suit_sub");
    local suitEffectLabel = CT:getChildByName("suit_effect");

    local suitId = equipInfo["suit"];
    if suitId and suitId ~= 0 then
        suitNameLabel:setVisible(true);
        suitSubLabel:setVisible(true);
        suitEffectLabel:setVisible(true);
    end

    -- 显示商品描述
    local desc = "";
    local detail = "";
    if suitId and suitId ~= 0 then

        -- 套装信息
        local suitInfo = SuitM.query(suitId);
        if not suitInfo then
            error("获取不到套装(%d)信息", suitId);
            return;
        end

        local suits = suitInfo["active"];
        local suitCount = #suits;
        local suitActiveCount = 0;
        if suits then
            suitSubLabel:setVisible(true);
            local suitSub = "";
            for i = 1, suitCount do
                local equipId = suits[i];
                local itemName = ItemM.query(equipId, "name");
                local type = EquipM.query(equipId, "type")
                if EquipM.getEquip(type) == equipId then
                    -- 已经装备了，显示激活的颜色
                    suitActiveCount = suitActiveCount + 1;
                    itemName = "[brown]" .. itemName .. "[-]";
                elseif table.indexOf(table.keys(EquipM.queryEquipments(type)), equipId) > 0 then
                    -- 有，但是没装备，显示绿色
                    itemName = "[green]" .. itemName .. "[-]";
                else
                    -- 完全没这件，显示灰色
                    itemName = "[gray]" .. itemName .. "[-]";
                end

                suitSub = suitSub .. itemName;
                if i ~= suitCount then
                    suitSub = suitSub .. "\n";
                end
            end

            TextStyleM.setTextStyle(suitSubLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_DARK_BROWN);
            suitSubLabel = applyString(suitSubLabel, suitSub);
        end

        -- 设置套装名字
        local suitNameTxt = suitInfo["name"] .. "(" .. suitActiveCount .. "/" .. suitCount .. ")";
        TextStyleM.setTextStyle(suitNameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
        suitNameLabel:setString(suitNameTxt);

        -- 设置套装效果 当套装效果未激活时，效果值显示为“？”；效果集齐时，显示具体属性
        local props = SuitM.calcSuitBaseProp(suitId);
        local suitEffect = EquipM.getEquipPropDesc(props);
        if suitActiveCount == suitCount then
            TextStyleM.setTextStyle(suitEffectLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE);
        else
            TextStyleM.setTextStyle(suitEffectLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GRAY);
        end
        suitEffectLabel = applyString(suitEffectLabel, suitEffect);
    elseif HolyItemsM.isHolyItems(classId) then
        -- 如果是圣器
        suitNameLabel:setVisible(true);
        suitSubLabel:setVisible(false);
        suitEffectLabel:setVisible(true);
        local level = HolyItemsM.getExtraLevel(classId);
        local maxLevel = HolyItemsM.query(classId, "max_extra_level");
        TextStyleM.setTextStyle(suitNameLabel, TextStyleM.TEXT_SIZE_MIDDLE, TextStyleM.TEXT_COLOR_DARK_RED);
        suitNameLabel:setString(string.format(getLocStr("holy_items_upgrade_title"), level, maxLevel));

        -- 获取圣器的特殊属性描述
        local desc = HolyItemsM.getExtraPropDesc(classId);
        if level > 0 then
            TextStyleM.setTextStyle(suitEffectLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_BLUE);
        else
            TextStyleM.setTextStyle(suitEffectLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GRAY);
        end
        suitEffectLabel = applyString(suitEffectLabel, desc);
    else
        suitNameLabel:setVisible(false);
        suitSubLabel:setVisible(false);
        suitEffectLabel:setVisible(false);
    end

    -- 显示商品价格
    local price = DungeonShopM.queryPrice(self.goodsId);
    local amountLabel = CT:getChildByName("own_amount");
    local costDesc = "";
    TextStyleM.setTextStyle(amountLabel, TextStyleM.TEXT_SIZE_SMALL, TextStyleM.TEXT_COLOR_GREEN);
    if string.startWith(self.shopType, "showcase") then
        -- 德古拉的展柜
        if price[1] == 1 then
            -- 物品消耗
            local payClassId = price[2];
            local payAmount  = price[3];
            local payName = ItemM.query(payClassId, "name");
            local ownAmount = ItemM.getAmount(ME.user, payClassId);
            local attribDesc = string.format(getLocStr("attrib_value_format"), ownAmount, payAmount);
            if payAmount > ownAmount then
                attribDesc = "[red]" .. attribDesc .. "[-]";
            end

            costDesc = string.format(getLocStr("unlock_seal_cost2"), payName, attribDesc);
        end
        amountLabel = applyString(amountLabel, costDesc);
    else
        if price[1] == 1 then
            -- 物品消耗
            local payClassId = price[2];
            local payAmount  = price[3];
            local payName = ItemM.query(payClassId, "name");
            local ownAmount = ItemM.getAmount(ME.user, payClassId);
            local attribDesc = string.format(getLocStr("attrib_value_format"), ownAmount, payAmount);
            if payAmount > ownAmount then
                attribDesc = "[red]" .. attribDesc .. "[-]";
            end

            costDesc = string.format(getLocStr("buy_cost_attrib2"), payName, attribDesc);
        elseif price[1] == 2 then
            -- 属性消耗
            local payAttrib   = price[2];
            local priceAmount = price[3];
            local ownAmount = ME.user:queryAttrib(payAttrib);
            local fieldName = FieldsM.getFieldName(payAttrib);
            local attribDesc = string.format(getLocStr("attrib_value_format"), ownAmount, priceAmount);
            if priceAmount > ownAmount then
                attribDesc = "[red]" .. attribDesc .. "[-]";
            end

            costDesc = string.format(getLocStr("buy_cost_attrib2"), fieldName, attribDesc);
        end

        costDesc = costDesc .. "\n";

        -- 显示拥有商品数量
        local amount = ItemM.getOwnedAmount(ME.user, classId);
        costDesc = costDesc .. string.format(getLocStr("own_goods_amount2"), amount);
        amountLabel = applyString(amountLabel, costDesc);
    end

    -- 自适应所有组件
    local bg = findChildByName(self.node, "CT/bg");
    local btnBuy = findChildByName(self.node, "CT/btn_buy");
    AlignM.adaptLayout(bg, AlignM.BG_SIZE_NORMAL,
        { nameLabel, descLabel, detailLabel, suitNameLabel,
          suitSubLabel, suitEffectLabel, amountLabel, btnBuy});

    -- 显示商品阶位
    local rank = ItemM.query(classId, "rank") or 0;
    if rank > 0 then
        local starNode = findChildByName(self.node, "CT/star_node");
        local layer = createStarLayer(rank, "images/ui/symbol/star_large.png", "right");
        if layer then
            starNode:removeAllChildren();
            starNode:addChild(layer);
        end
        starNode:setPositionY(nameLabel:getPositionY());
    end
end

-- 适配
function UIDungeonGoodsEquip:resize()
    local node = self.node;

    -- bg居中显示并充满整个屏幕
    AlignM.fitToScreen(node, "bg");

    -- CT居中并缩放至合适大小
    AlignM.alignToCenter(node, "CT");

    -- BT置于底部并缩放至合适大小
    AlignM.alignToBottomCenter(node, "BT");
end

-- 尝试购买
function UIDungeonGoodsEquip:tryBuy()
    -- 判断能否购买
    local ret = DungeonShopM.canBuyGoods(self.shopType .. self.pos, self.goodsIndex);
    if ret ~= true then
        AudioM.playFx("market_buy_failed");

        if ret == "sold_out" then
            -- 商品已售完
            alert(getLocStr("goods_sold_out"));
        elseif string.endWith(ret, "_lack") then
            -- 消耗不足
            local price = DungeonShopM.queryPrice(self.goodsId);

            if price[1] == 1 then
                -- 物品消耗
                local payClassId = price[2];
                local payAmount  = price[3];
                local payName = ItemM.query(payClassId, "name");
                local msg = "";
                if string.startWith(self.shopType, "showcase") then
                    msg = string.format(getLocStr("something_not_enough"), payName);
                else
                    msg = string.format(getLocStr("fail_to_do_operate"), payName, getLocStr("buy"));
                end
                alert(msg);
            elseif price[1] == 2 then
                -- 属性消耗
                local payAttrib   = price[2];
                local priceAmount = price[3];
                local fieldName = FieldsM.getFieldName(payAttrib);
                local msg = string.format(getLocStr("fail_to_do_operate"), fieldName, getLocStr("buy"));
                alert(msg);
            end
        else
            -- 未知原因
            cclog("购买商品失败，原因：" .. ret );
        end

        -- 关闭当前界面
        UIMgr.getCurrentScene():removeFormByName(self:getName());
        return;
    end

    -- 执行购买
    AudioM.playFx("market_buy_success");
    DungeonActionM.go("buy_goods", self.pos, self.goodsIndex);

    -- 关闭当前界面
    UIMgr.getCurrentScene():removeFormByName(self:getName());
end

